import authority from './authority'
import { redirectLogin } from './router'
import * as ShopApi from '../api/shop'
import location from './location'
import { isWx } from '@/utils/validate'

export default async () => {
  // 取缓存shop_id
  let { city = {} } = authority.get() || {}
  const { shop_id } = city
  if (shop_id) return shop_id

  // 获取店铺列表
  const { shop = [] } = await ShopApi.list()

  // 只有一个店铺的自动获取第一个店铺shop_id
  if (shop.length === 1) {
    city = shop[0]
  } else {
    // 自动定位所在城市店铺
    const { currentAddress = {} } = authority.get() || {}
    let { currentCode } = currentAddress
    if (!currentCode && isWx) {
      const locationData = await location.get()
      currentCode = locationData.currentCode
    }
    city =
      shop.find(item => item.region_code === currentAddress.currentCode) || {}
  }

  if (city.shop_id) {
    authority.set({
      city
    })
    return city.shop_id
  } else {
    // 没有返回报错
    return redirectLogin('chooseCity')
  }
}
